import { Node, mergeAttributes } from '@tiptap/core'

export default Node.create({
  name: 'image',

  addOptions() {
    return {
      inline: false,
      allowBase64: false,
      HTMLAttributes: {}
    }
  },

  inline() {
    return this.options.inline
  },

  group() {
    return this.options.inline ? 'inline' : 'block'
  },

  draggable: true,

  addAttributes() {
    return {
      src: {
        default: null
      },
      alt: {
        default: null
      },
      title: {
        default: null
      },
      width: {
        default: null
      },
      height: {
        default: null
      },
      style: {
        default: null
      },
      href: {
        default: null
      },
      target: {
        default: null
      }
    }
  },

  parseHTML() {
    return [
      {
        tag: this.options.allowBase64
          ? 'img[src]'
          : 'img[src]:not([src^="data:"])',
        getAttrs: (dom) => {
          const img = dom.tagName === 'IMG' ? dom : dom.querySelector('img')
          if (!img) return false

          const parent = img.parentElement
          const attrs = {
            src: img.getAttribute('src'),
            alt: img.getAttribute('alt'),
            title: img.getAttribute('title'),
            width: img.getAttribute('width'),
            height: img.getAttribute('height'),
            style: img.getAttribute('style')
          }

          // 如果父元素是a标签，获取链接属性
          if (parent && parent.tagName === 'A') {
            attrs.href = parent.getAttribute('href')
            attrs.target = parent.getAttribute('target')
          }

          return attrs
        }
      },
      {
        tag: 'a img',
        getAttrs: (dom) => {
          const img = dom.querySelector('img')
          if (!img) return false

          return {
            src: img.getAttribute('src'),
            alt: img.getAttribute('alt'),
            title: img.getAttribute('title'),
            width: img.getAttribute('width'),
            height: img.getAttribute('height'),
            style: img.getAttribute('style'),
            href: dom.getAttribute('href'),
            target: dom.getAttribute('target')
          }
        }
      }
    ]
  },

  renderHTML({ HTMLAttributes }) {
    const { href, target, ...imgAttrs } = HTMLAttributes
    const img = ['img', mergeAttributes(this.options.HTMLAttributes, imgAttrs)]

    // 如果有链接，将图片包装在a标签中
    if (href) {
      const linkAttrs = { href }
      if (target) linkAttrs.target = target
      return ['a', linkAttrs, img]
    }

    return img
  },

  addNodeView() {
    return ({ node, HTMLAttributes, getPos, editor }) => {
      const { href, target, ...imgAttrs } = HTMLAttributes
      const img = document.createElement('img')

      // 设置图片属性
      Object.entries(imgAttrs).forEach(([key, value]) => {
        if (value !== null && value !== undefined) {
          img.setAttribute(key, value)
        }
      })

      // 添加样式和类名
      img.style.maxWidth = '100%'
      img.style.height = 'auto'
      img.style.cursor = 'pointer'
      img.contentEditable = 'false'
      img.draggable = true
      img.classList.add('custom-image')

      // 创建包装元素（如果有链接）
      let wrapper = img
      if (href) {
        const link = document.createElement('a')
        link.setAttribute('href', href)
        if (target) link.setAttribute('target', target)
        link.contentEditable = 'false'
        link.appendChild(img)
        wrapper = link
      }

      // 添加点击事件处理
      img.addEventListener('click', (event) => {
        event.preventDefault()
        event.stopPropagation()

        // 获取组件实例
        const component = editor.storage.component
        if (component) {
          const pos = getPos()
          if (pos !== undefined) {
            // 选中图片节点
            editor.commands.setNodeSelection(pos)

            // 强制更新组件状态
            setTimeout(() => {
              component.updateCurrentElementType()
              component.updateImageState()
              component.updateFloatingToolbar()

              console.log('图片点击后状态：', {
                isImageSelected: component.isImageSelected,
                selectedImageUrl: component.selectedImageUrl,
                selectedImageHref: node.attrs.href,
                showFloatingToolbar: component.showFloatingToolbar
              })
            }, 10)
          }
        }
      })

      // 添加选中状态样式
      const updateSelection = () => {
        const { selection } = editor.state
        const pos = getPos()

        // 检查是否是节点选择且选中的是当前图片节点
        if (pos !== undefined && selection.from === pos && selection.to === pos + node.nodeSize) {
          img.classList.add('ProseMirror-selectednode')
          console.log('图片选中，添加边框样式', pos)
        } else {
          img.classList.remove('ProseMirror-selectednode')
        }
      }

      // 监听选择变化
      editor.on('selectionUpdate', updateSelection)
      updateSelection()

      return {
        dom: wrapper,
        destroy() {
          editor.off('selectionUpdate', updateSelection)
        }
      }
    }
  },

  addCommands() {
    return {
      setImage: options => ({ commands }) => {
        return commands.insertContent({
          type: this.name,
          attrs: options
        })
      }
    }
  }
})
